<template>
  <div class="main-con flex1 vbox">
    <!-- <el-col :span="6">
        <el-card>
          <div class="toolbar">
            <el-button icon="el-icon-plus" type="success" @click="showAdminGroupAddDialog">新增组</el-button>
            <span style="color:#999;font-size:14px;padding-left:20px;">
              <el-switch v-model="allowEditGroup"></el-switch>
              <span style="padding-left:5px;">编辑</span>
            </span>
          </div>
          <div style="padding:12px">
            <admin-group-tree
              ref="adminGroupTree"
              :allowEditGroup="allowEditGroup"
              @node-click="nodeClick"
              @edit-group="editGroup"
            ></admin-group-tree>
          </div>
        </el-card>
    </el-col>-->
    <div class="search-con">
      <el-form :model="searchParam" :inline="true">
        <el-form-item prop="username">
          <el-input
            v-model.trim="searchParam.username"
            @keyup.enter.native="search"
            placeholder="输入管理员账号"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="vbox flex1">
      <div class="toolbar">
        <el-button type="primary" v-auth="'add'" plain icon="el-icon-plus" @click="showDialog">添加管理员</el-button>
      </div>
      <base-table
        ref="adminTable"
        url="admin/page"
        :cls="columns"
        :optionBtns="optionBtns"
        @handlerOption="handlerOption"
      ></base-table>
    </div>
    <el-dialog title="添加组" :visible.sync="showAdminGroupDialog" :width="'30%'">
      <el-form ref="adminGroupForm" :model="admin" :rules="groupRules" label-width="95px">
        <el-form-item label="父分组" prop="parentId">
          <el-tree-select
            v-model="adminGroup.parentId"
            :url="groupTreeUrl"
            label="name"
            placeholder="请选择用户组"
          ></el-tree-select>
        </el-form-item>
        <el-form-item label="分组名" prop="name">
          <el-input v-model.trim="adminGroup.name" placeholder="请输入分组名称"></el-input>
        </el-form-item>
        <el-form-item label="选择权限">
          <res-tree ref="resTree" :showCheckbox="true" @check="onCheck"></res-tree>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showAdminGroupDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveAdminGroup">保 存</el-button>
      </span>
    </el-dialog>
    <el-dialog center title="添加/编辑账号" :visible.sync="showAdminDialog" :width="'30%'" top="1%">
      <el-form ref="adminForm" :model="admin" :rules="rules" label-width="95px">
        <el-form-item label="登录名" prop="username">
          <el-input v-model.trim="admin.username" clearable placeholder="请输入登录账号"></el-input>
        </el-form-item>
        <el-form-item v-if="!admin.id" label="密码" prop="password">
          <el-input show-password v-model.trim="admin.password" clearable placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item label="客户编码" prop="orgId">
          <el-select
            clearable
            filterable
            style="width:100%"
            :filter-method="filterMethod"
            v-model="admin.orgId"
            placeholder="请选择客户"
          >
            <el-option
              v-for="item in consumerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.code }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择角色" prop="roleIds">
          <el-select style="width:100%" v-model="admin.roleIds" multiple placeholder="请选择角色">
            <el-option v-for="role in roles" :key="role.id" :label="role.roleName" :value="role.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="账号类型" prop="type">
          <base-select v-model="admin.type" dictCode="admin_type"></base-select>
        </el-form-item>
        <el-form-item label="折扣" prop="discount">
          <el-input-number
            style="width:70%"
            :max="1"
            v-model="admin.discount"
            :precision="2"
            placeholder="可享受的折扣"
          ></el-input-number>
        </el-form-item>
        <!-- <el-form-item label="选择用户组" prop="groupId">
          <el-tree-select
            v-model="admin.groupId"
            :url="groupTreeUrl"
            label="name"
            placeholder="请选择用户组"
          ></el-tree-select>
        </el-form-item>-->
        <el-form-item label="账号描述" prop="remark">
          <el-input v-model.trim="admin.remark" placeholder="请输入账号描述"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model.trim="admin.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model.trim="admin.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-col :span="8">
            <el-radio-group v-model="admin.sex">
              <el-radio-button label="男">男</el-radio-button>
              <el-radio-button label="女">女</el-radio-button>
            </el-radio-group>
          </el-col>
          <el-col :span="16">
            <el-form-item label-width="90px" label="可操作" prop="editabled">
              <el-radio-group v-model="admin.editabled">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveAdmin">保 存</el-button>
        <el-button @click="showAdminDialog = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    let me = this;
    return {
      showAdminDialog: false,
      showAdminGroupDialog: false,
      allowEditGroup: false,
      searchParam: {
        username: ""
      },
      choseAdminGroup: null,
      groupTreeUrl: "group/getGroupTree/" + me.$store.state.admin.orgId,
      admin: {
        id: "",
        password: "",
        username: "",
        remark: "",
        phone: "",
        editabled: 1,
        email: "",
        sex: "男",
        groupId: "",
        roleIds: [],
        type: "1",
        discount: 1,
        orgId: ""
      },
      adminGroup: {
        id: "",
        parentId: "",
        name: "",
        orgId: "",
        parentName: "",
        resInfo: []
      },
      groupRules: {
        parentId: [
          {
            type: "number",
            required: true,
            message: "请选择父节点",
            trigger: ["change", "blur"]
          }
        ]
      },
      rules: {
        username: [
          {
            required: true,
            message: "请输入账号名称",
            trigger: ["change", "blur"]
          }
        ],
        password: [
          {
            required: true,
            message: "请输入账号密码",
            trigger: ["change", "blur"]
          }
        ],
        orgId: [
          {
            required: true,
            message: "请选择客户编码",
            trigger: ["change", "blur"]
          }
        ],
        roleIds: [
          {
            required: true,
            message: "请选择用户组",
            trigger: ["change", "blur"],
            type: "array"
          }
        ]
      },
      columns: [
        { prop: "id", label: "编号", width: 100 },
        { prop: "username", label: "账号名称", width: 120 },
        { prop: "phone", label: "手机号", width: 150 },
        { prop: "remark", label: "账号描述", width: 180 },
        { prop: "crteTime", label: "创建时间", width: 180 },
        {
          prop: "editabled",
          label: "是否可操作",
          formatter(record) {
            return record.editabled == 0 ? "否" : "是";
          }
        }
      ],
      optionBtns: [
        { text: "编辑", code: "list_edit", type: "primary" },
        { text: "删除", code: "list_delete" }
      ],
      checkedKeys: [],
      expandKeys: [],
      roles: [],
      parentConsumers: [],
      consumerOptions: []
    };
  },
  activated() {
    this.getByCrteAdminId();
    this.getParentConsumers();
  },
  methods: {
    onCheck(
      data,
      { checkedNodes, checkedKeys, halfCheckedNodes, halfCheckedKeys }
    ) {
      let resInfo = [];
      checkedKeys.forEach(item => {
        resInfo.push({
          resId: item,
          leaf: 1
        });
      });
      halfCheckedKeys.forEach(item => {
        resInfo.push({
          resId: item,
          leaf: 0
        });
      });
      this.adminGroup.resInfo = resInfo;
    },
    initCheckedKeys(keys) {
      let resInfo = [];
      keys.forEach(item => {
        resInfo.push({
          resId: item.resId,
          leaf: item.leaf
        });
      });
      this.adminGroup.resInfo = resInfo;
    },
    showAdminGroupAddDialog() {
      this.showAdminGroupDialog = true;
      this.$nextTick(() => {
        this.$refs.adminGroupForm.resetFields();
        this.adminGroup.name = "";
        this.adminGroup.parentId = "";
        this.adminGroup.parentName = "";
        this.$refs.resTree.setCheckedKeys([]);
      });
    },
    editGroup(data) {
      let tempData = Object.assign({}, data);
      this.adminGroup = tempData;
      this.showAdminGroupDialog = true;
      this.$nextTick(() => {
        this.$refs.resTree.setCheckedKeys([]);
        this.getResByGroupId(data);
      });
    },
    getResByGroupId(data) {
      let me = this;
      me.$http.ajax({
        url: "group/getResIdByGroupId",
        data: [data.id],
        success: res => {
          me.$refs.resTree.setCheckedKeys(res);
        }
      });
    },
    getByCrteAdminId() {
      let me = this;
      me.$http.ajax({
        url: "admin/getByCrteAdminId/" + me.$store.state.admin.id,
        success: res => {
          me.roles = res;
        }
      });
    },
    getRoleIdsByAdminId(adminId) {
      let me = this;
      me.$http.ajax({
        url: "admin/getRoleIdsByAdminId/" + adminId,
        success: res => {
          me.admin.roleIds = res;
        }
      });
    },
    handlerOption(code, row) {
      if (code == "list_edit") {
        this.eidtAdmin(row);
      } else if (code == "list_delete") {
        this.delAdmin(row);
      }
    },
    showDialog() {
      this.showAdminDialog = true;
      this.$nextTick(() => {
        this.$refs["adminForm"].resetFields();
        this.admin = {
          id: "",
          username: "",
          remark: "",
          phone: "",
          editabled: 1,
          email: "",
          sex: "男",
          roleIds: [],
          type: "1",
          discount: 1
        };
      });
    },
    eidtAdmin(row) {
      let me = this;
      me.showAdminDialog = true;
      me.$nextTick(() => {
        let tempData = Object.assign({}, row);
        tempData.type = tempData.type + "";
        tempData.roleIds = [];
        me.admin = tempData;
        me.admin.password = "";
        me.getRoleIdsByAdminId(tempData.id);
      });
    },
    delAdmin(row) {
      let me = this;
      me.$confirm("确定要删除选中行数据吗?", "操作提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        me.$http.ajax({
          url: "admin/delete",
          data: {
            ids: [row.id]
          },
          success: res => {
            me.$message.success("删除成功");
            me.search();
          }
        });
      });
    },
    search() {
      this.$refs["adminTable"].initLoad();
    },
    saveAdmin() {
      let me = this;
      me.$refs["adminForm"].validate(valid => {
        if (valid) {
          me.$http.ajax({
            url: "admin/save",
            data: me.admin,
            success: res => {
              me.$message.success("保存成功");
              me.showAdminDialog = false;
              me.search();
            }
          });
        }
      });
    },
    loadAdminGroup() {
      this.$refs["adminGroupTree"].loadData();
    },
    saveAdminGroup() {
      let me = this;
      me.$refs["adminGroupForm"].validate(valid => {
        if (valid) {
          me.$http.ajax({
            url: "group/save",
            data: me.adminGroup,
            success: res => {
              me.$message.success("保存成功");
              me.showAdminGroupDialog = false;
              me.loadAdminGroup();
            }
          });
        }
      });
    },
    nodeClick(data, node, component) {
      let me = this;
      let tempData = Object.assign({}, data);
      me.choseAdminGroup = tempData;
      me.adminGroup.parentId = data.id;
      me.adminGroup.parentName = data.name;
    },
    getParentConsumers() {
      let me = this;
      me.$http.ajax({
        url: "consumer/listChildren/" + me.$store.state.admin.orgId,
        success: res => {
          me.parentConsumers = res;
          me.consumerOptions = res;
        }
      });
    },
    filterMethod(query) {
      let me = this;
      if (!query.trim()) {
        me.consumerOptions = me.parentConsumers;
      } else {
        me.consumerOptions = me.parentConsumers.filter(consumer => {
          return (
            consumer.name.toLowerCase().indexOf(query.toLowerCase()) > -1 ||
            consumer.code.toLowerCase().indexOf(query.toLowerCase()) > -1
          );
        });
      }
    }
  }
};
</script>

<style>
</style>
